

#import "QRCodeReaderViewController.h"
#import "QRCameraSwitchButton.h"
#import "QRCodeReaderView.h"
#import <AVFoundation/AVFoundation.h> //手电筒

#define mainHeight     [[UIScreen mainScreen] bounds].size.height
#define mainWidth      [[UIScreen mainScreen] bounds].size.width
#define navBarHeight   self.navigationController.navigationBar.frame.size.height

@interface QRCodeReaderViewController () <AVCaptureMetadataOutputObjectsDelegate,QRCodeReaderViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
///手电筒🔦
{
    BOOL isLightOn;
    AVCaptureDevice *device;
    UIView *_topView;
    UIView *_topbgView;
}
@property BOOL _isLightOn;
@property (strong, nonatomic) QRCameraSwitchButton *switchCameraButton;
@property (strong, nonatomic) QRCodeReaderView     *cameraView;
@property (strong, nonatomic) AVAudioPlayer        *beepPlayer;
@property (strong, nonatomic) UIButton             *cancelButton;
@property (strong, nonatomic) UIImageView          *imgLine;
@property (strong, nonatomic) UILabel              *lblTip;

@property (strong,nonatomic) UIButton             *imageSelectBtn;

@property (strong, nonatomic) NSTimer              *timerScan;
@property (strong, nonatomic) UIButton             *btn;//🔦
@property (strong, nonatomic) AVCaptureDevice            *defaultDevice;
@property (strong, nonatomic) AVCaptureDeviceInput       *defaultDeviceInput;
@property (strong, nonatomic) AVCaptureDevice            *frontDevice;
@property (strong, nonatomic) AVCaptureDeviceInput       *frontDeviceInput;
@property (strong, nonatomic) AVCaptureMetadataOutput    *metadataOutput;
@property (strong, nonatomic) AVCaptureSession           *session;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer *previewLayer;

@property (strong, nonatomic) CIDetector *detector;

@property (strong, nonatomic) UIView * naviBgView;


@property (copy, nonatomic) void (^completionBlock) (NSString *);

@property (nonatomic,strong) UIImageView *pickImage;

@property (nonatomic,strong) UITextView *swipResult;


@end

@implementation QRCodeReaderViewController

- (id)init
{
    self = [super init];
    NSString * wavPath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"wav"];
    NSData* data = [[NSData alloc] initWithContentsOfFile:wavPath];
    _beepPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
    
    return [self initWithCancelButtonTitle:NSLocalizedString(@"Cancel", @"Cancel")];
}

- (id)initWithCancelButtonTitle:(NSString *)cancelTitle
{
    if ((self = [super init])) {
        self.view.backgroundColor = [UIColor clearColor];

        [self setupAVComponents];
        [self configureDefaultComponents];
        [self setupUIComponentsWithCancelButtonTitle:cancelTitle];
        [self setupAutoLayoutConstraints];
        [_cameraView.layer insertSublayer:self.previewLayer atIndex:0];
    }
    return self;
}

+ (instancetype)readerWithCancelButtonTitle:(NSString *)cancelTitle
{
  return [[self alloc] initWithCancelButtonTitle:cancelTitle];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}
- (void)createTopBackGroundView
{
    _topView  = [[UIView alloc]init];
    _topView.frame = CGRectMake(self.view.bounds.size.width*2/3, 0, self.view.bounds.size.width/3, _topbgView.frame.size.height-5);
    
    UIImageView *imageview = [[UIImageView alloc]initWithFrame:_topView.bounds];
    imageview.image =[UIImage imageNamed:@"icon_background_light"];
    imageview.backgroundColor = [UIColor clearColor];
    [_topView addSubview:imageview];
    _topView.userInteractionEnabled = YES;
    _topView.backgroundColor = [UIColor clearColor];
    
    _topView.hidden = YES;
    
    UIButton *topBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, _topView.frame.size.width, (_topView.frame.size.height-10)/2)];
    [topBtn setTitle:@"开启闪光灯" forState:UIControlStateNormal];
    [topBtn setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.8] forState:UIControlStateNormal];
    topBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    topBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [topBtn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:topBtn];
    
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(10, (_topView.frame.size.height-10)/2+10, _topView.frame.size.width-20, 0.5)];
    line.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0.3];
    [_topView addSubview:line];
    
    UIButton *bottomBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, (_topView.frame.size.height-15)/2+10, _topView.frame.size.width, (_topView.frame.size.height-10)/2)];
    [bottomBtn setTitle:@"扫描图片" forState:UIControlStateNormal];
    [bottomBtn setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.8] forState:UIControlStateNormal];
    bottomBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    bottomBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [bottomBtn addTarget:self action:@selector(clickRightBarButton:) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:bottomBtn];
    
    [_topbgView addSubview:_topView];
}
- (void)createBackgroundViews
{
    _topbgView = [[UIView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, Frame_Width, _cameraView.innerViewRect.origin.y-NAVIGATION_BAR_HEIGHT+22)];
    _topbgView.backgroundColor = COLOR_R_G_B_A(0, 0, 0, 0.6);
    [self.view addSubview:_topbgView];
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, _cameraView.innerViewRect.origin.y+22, 49, _imgLine.frame.size.width)];
    leftView.backgroundColor = COLOR_R_G_B_A(0, 0, 0, 0.6);
    [self.view addSubview:leftView];
    
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(_imgLine.frame.size.width+49, _cameraView.innerViewRect.origin.y+22, 49, _imgLine.frame.size.width)];
    rightView.backgroundColor = COLOR_R_G_B_A(0, 0, 0, 0.6);
    [self.view addSubview:rightView];
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _cameraView.innerViewRect.origin.y+22+_imgLine.frame.size.width, Frame_Width, Frame_HEIGHT)];
    bottomView.backgroundColor = COLOR_R_G_B_A(0, 0, 0, 0.6);
    [self.view addSubview:bottomView];
    
     _cropRect = CGRectMake(leftView.frame.size.width,_topbgView.frame.origin.y+_topbgView.frame.size.height,rightView.frame.origin.x-leftView.frame.size.width,rightView.frame.origin.x-leftView.frame.size.width);
    
    CGSize size = self.view.bounds.size;
    
    [_metadataOutput setRectOfInterest:CGRectMake(_cropRect.origin.y/SCREEN_HEIGHT,
                                                  _cropRect.origin.x/size.width,
                                                  _cropRect.size.height/size.height,
                                                  _cropRect.size.width/size.width)];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
//    [self.view addSubview:self.naviBgView];
//    [self setNavigationBarBackgroudColor:RGBA(106, 137, 165, 1)];
//    if ([_QRCodeType intValue]==1) {
//        [self setCustomNaviWithLeftItemTitle:nil leftItemImageName:@"nav_fanhui"  naviTitle:@"扫一扫" centerImageName:nil rightItemTitle:nil rightItemImageName:nil];
//    }else{
//        [self setCustomNaviWithLeftItemTitle:nil leftItemImageName:@"nav_fanhui"  naviTitle:@"扫一扫" centerImageName:nil rightItemTitle:nil rightItemImageName:nil];
//    }

    [self startScanning];
}

-(UIView*)naviBgView{
    if (!_naviBgView) {
        _naviBgView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, Main_Screen_Width, 64)];
        [_naviBgView setBackgroundColor:[UIColor blackColor]];
        [_naviBgView setAlpha:1.0];
    }
    return _naviBgView;
}


-(void)leftButtonItemTapped{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
  [self stopScanning];
  [super viewWillDisappear:animated];
}
- (void)topToViewClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    _topView.hidden = (NO)?sender.selected :!sender.selected;
}
- (void)viewWillLayoutSubviews
{
  [super viewWillLayoutSubviews];
}

- (BOOL)shouldAutorotate
{
  return YES;
}

- (void)scanAnimate
{
    _imgLine.frame = CGRectMake(49, _cameraView.innerViewRect.origin.y+18, mainWidth-98, 12);
    [UIView animateWithDuration:2 animations:^{
        _imgLine.frame = CGRectMake(_imgLine.frame.origin.x, _imgLine.frame.origin.y + _cameraView.innerViewRect.size.height-5
                                    , _imgLine.frame.size.width, _imgLine.frame.size.height);
    }];
}

- (void)loadView:(CGRect)rect
{
    _previewLayer.frame = self.view.layer.bounds;
    _imgLine.frame = CGRectMake(49, _cameraView.innerViewRect.origin.y+18, mainWidth-98, 12);
    [self scanAnimate];
    [self createBackgroundViews];
    [self createTopBackGroundView];
    [self.view bringSubviewToFront:_lblTip];

}

#pragma mark - Managing the Orientation

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
  [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
  
  [_cameraView setNeedsDisplay];
  
  if (self.previewLayer.connection.isVideoOrientationSupported) {
    self.previewLayer.connection.videoOrientation = [[self class] videoOrientationFromInterfaceOrientation:toInterfaceOrientation];
  }
}

+ (AVCaptureVideoOrientation)videoOrientationFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
  switch (interfaceOrientation) {
    case UIInterfaceOrientationLandscapeLeft:
      return AVCaptureVideoOrientationLandscapeLeft;
    case UIInterfaceOrientationLandscapeRight:
      return AVCaptureVideoOrientationLandscapeRight;
    case UIInterfaceOrientationPortrait:
      return AVCaptureVideoOrientationPortrait;
    default:
      return AVCaptureVideoOrientationPortraitUpsideDown;
  }
}

#pragma mark - Managing the Block

- (void)setCompletionWithBlock:(void (^) (NSString *resultAsString))completionBlock
{
    self.completionBlock = completionBlock;
}

#pragma mark - Initializing the AV Components

- (void)setupUIComponentsWithCancelButtonTitle:(NSString *)cancelButtonTitle
{
    self.cameraView = [[QRCodeReaderView alloc] init];
    _cameraView.translatesAutoresizingMaskIntoConstraints = NO;
    _cameraView.clipsToBounds  = YES;
    _cameraView.delegate = self;
    [self.view addSubview:_cameraView];

    self.cancelButton = [[UIButton alloc] init];
    self.cancelButton.hidden = YES;
    _cancelButton.translatesAutoresizingMaskIntoConstraints = NO;
    [_cancelButton setTitle:cancelButtonTitle forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [_cancelButton addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelButton];
    
    CGFloat c_width = mainWidth - 100;
    CGFloat s_height = mainHeight - 40;
    CGFloat y = (s_height - c_width) / 2 - s_height / 6;
    
    _lightIcon = [[UIImageView alloc]initWithFrame:CGRectMake(mainWidth/2-10,y + 20+ c_width , 20, 30)];
    [_lightIcon setImage:[UIImage imageNamed:@"lightning"]];
    [_lightIcon setAlpha:0.0];
    [self.view  addSubview:_lightIcon];
    
    _topBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, y + 60 + c_width , mainWidth, 15)];
    [_topBtn setTitle:@"轻触照亮" forState:UIControlStateNormal];
    [_topBtn setTitleColor:[UIColor colorWithWhite:1.0 alpha:1.0] forState:UIControlStateNormal];
    _topBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    _topBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [_topBtn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    [_topBtn setAlpha:0.0];
    [self.view  addSubview:_topBtn];
    
    _lightButton = [[UIButton alloc]initWithFrame:CGRectMake(mainWidth/2-20,y + 20+ c_width, 40, 45)];
    _lightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_lightButton addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    [_lightButton setEnabled:NO];
    [self.view  addSubview:_lightButton];
    
    _lblTip = [[UILabel alloc] initWithFrame:CGRectMake(0, y + 140 + c_width , mainWidth, 15)];
    _lblTip.textColor = [UIColor colorWithWhite:1.0 alpha:1];
    _lblTip.font = [UIFont systemFontOfSize:15];
    _lblTip.textAlignment = NSTextAlignmentCenter;
    _lblTip.text = @"将二维码放入框内，即可自动扫描";
    [self.view addSubview:_lblTip];
    
    _imageSelectBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, y + c_width , mainWidth, 15)];
    _imageSelectBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_imageSelectBtn setTitle:@"从相册选取" forState:UIControlStateNormal];
    _imageSelectBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_imageSelectBtn addTarget:self action:@selector(pickImageToSwip) forControlEvents:UIControlEventTouchUpInside];
    [_imageSelectBtn setTitleColor:[UIColor colorWithWhite:1.0 alpha:1.0] forState:UIControlStateNormal];
    _imageSelectBtn.enabled = YES;
//    _imageSelectBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
//    [_imageSelectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
//    [_imageSelectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.view addSubview:_imageSelectBtn];
//    _imageSelectBtn.frame = CGRectMake(0, y+140+c_width+60, mainWidth, 15);
    
    //🔦
    device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    CGFloat corWidth = 23;

    UIImageView* img1 = [[UIImageView alloc] initWithFrame:CGRectMake(49, y + 100, corWidth, corWidth)];
    img1.image = [UIImage imageNamed:@"icon_scan_lefttop"];
    [self.view addSubview:img1];
    
    UIImageView* img2 = [[UIImageView alloc] initWithFrame:CGRectMake(28 + c_width, y + 100, corWidth, corWidth)];
    img2.image = [UIImage imageNamed:@"icon_scan_righttop"];
    [self.view addSubview:img2];
    
    UIImageView* img3 = [[UIImageView alloc] initWithFrame:CGRectMake(49, y + c_width + 81, corWidth, corWidth)];
    img3.image = [UIImage imageNamed:@"icon_scan_leftbottom"];
    [self.view addSubview:img3];
    
    UIImageView* img4 = [[UIImageView alloc] initWithFrame:CGRectMake(28 + c_width, y + c_width + 81, corWidth, corWidth)];
    img4.image = [UIImage imageNamed:@"icon_scan_rightbottom"];
    [self.view addSubview:img4];
    
    
    _imgLine = [[UIImageView alloc] init];
    _imgLine.image = [UIImage imageNamed:@"icon_scan_center"];
    [self.view addSubview:_imgLine];
    
    _pickImage = [[UIImageView alloc]init];
    _pickImage.frame = CGRectMake(0, SafeAreaTopHeight, ScreenWidth, ScreenHeight-200-SafeAreaTopHeight);
    [self.view addSubview:_pickImage];
    _pickImage.hidden = YES;
    
    _swipResult = [[UITextView alloc]init];
    _swipResult.editable = NO;
    _swipResult.frame = CGRectMake(0, SCREEN_HEIGHT-200, ScreenWidth, 200);
    [self.view addSubview:_swipResult];
    _swipResult.hidden = YES;
    
}

-(void)pickImageToSwip
{
    self.detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];

    __weak typeof(self) ws = self;
    TZImagePickerController *picker = [[TZImagePickerController alloc]init];
    picker.allowPickingImage = YES;
    picker.allowTakeVideo = NO;
    picker.allowPreview = NO;
    picker.allowPickingGif = NO;
    picker.allowPickingVideo = NO;
    picker.allowTakePicture = NO;
    picker.allowTakeVideo = NO;
    picker.maxImagesCount = 1;
    [picker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        UIImage *image = photos.firstObject;
        NSArray *features = [ws.detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
        ws.pickImage.image = image;
        ws.pickImage.hidden = NO;
        
        
        if (features.count >=1) {
            CIQRCodeFeature *feature = [features objectAtIndex:0];
            NSString *scannedResult = feature.messageString;
            ws.swipResult.text = scannedResult;
            ws.swipResult.hidden = NO;
            if (ws.completionBlock) {
//                [ws.beepPlayer play];
                ws.completionBlock(scannedResult);
            }
            
            if (ws.delegate && [ws.delegate respondsToSelector:@selector(reader:didScanResult:)]) {
                [ws.delegate reader:ws didScanResult:scannedResult];
            }
        }
        else
        {
            DebugLog(@"什么也没识别到");
        }
    }];
    [self presentViewController:picker animated:YES completion:^{
            
    }];
}

- (void)loginNOScan
{
    ALERT_THREE(@"当前设备没有闪光灯，不能提供手电筒功能")
}
- (void)btnClicked
{
    if (![device hasFlash]) {//判断是否有闪光灯
        [self performSelectorOnMainThread:@selector(loginNOScan) withObject:nil waitUntilDone:NO];
        
        isLightOn = NO;
    }
    isLightOn = 1 - isLightOn;
    if (isLightOn)
    {
        [self turnOnLed:YES];
        [self.lightIcon setImage:[UIImage imageNamed:@"lightningon"]];
        [_topBtn setTitle:@"轻触关闭" forState:UIControlStateNormal];
    }
    else
    {
        [self turnOffLed:YES];
        [self.lightIcon setImage:[UIImage imageNamed:@"lightning"]];
        [_topBtn setTitle:@"轻触照亮" forState:UIControlStateNormal];
    }
}
// 打开手电筒
- (void)turnOnLed:(BOOL)update
{
    [device lockForConfiguration:nil];
    [device setTorchMode:AVCaptureTorchModeOn];
    [device unlockForConfiguration];

}
//关闭手电筒
- (void)turnOffLed:(BOOL)update
{
    [device lockForConfiguration:nil];
    [device setTorchMode:AVCaptureTorchModeOff];
    [device unlockForConfiguration];
    
}

-(void)setQRCodeType:(NSNumber *)QRCodeType{
    _QRCodeType = QRCodeType;
    if ([QRCodeType intValue]==1) {
        _lblTip.text = @"将二维码放入框内，即可自动扫描";
//        [self setCustomNaviWithLeftItemTitle:nil leftItemImageName:@"nav_fanhui"  naviTitle:@"扫描绑定码" centerImageName:nil rightItemTitle:nil rightItemImageName:nil];
    }else{
        _lblTip.text = @"将二维码放入框内，即可自动扫描";
    }
}

- (void)setupAutoLayoutConstraints
{
  NSDictionary *views = NSDictionaryOfVariableBindings(_cameraView, _cancelButton);
  
  [self.view addConstraints:
   [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_cameraView][_cancelButton(0)]|" options:0 metrics:nil views:views]];
  [self.view addConstraints:
   [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_cameraView]|" options:0 metrics:nil views:views]];
  [self.view addConstraints:
   [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_cancelButton]-|" options:0 metrics:nil views:views]];
  
}

- (void)setupAVComponents
{
  self.defaultDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  
  if (_defaultDevice) {
    self.defaultDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:_defaultDevice error:nil];
    self.metadataOutput     = [[AVCaptureMetadataOutput alloc] init];
      //初始化链接对象
//      self.metadataOutput.rectOfInterest = CGRectMake(, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>)
      
    self.session            = [[AVCaptureSession alloc] init];
       //高质量采集率
      [self.session setSessionPreset:AVCaptureSessionPresetHigh];
      
    self.previewLayer       = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    
    for (AVCaptureDevice *device2 in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
      if (device2.position == AVCaptureDevicePositionFront) {
        self.frontDevice = device2;
      }
    }
    
    if (_frontDevice) {
      self.frontDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:_frontDevice error:nil];
    }
  }
}

- (AVCaptureVideoDataOutput *)myVideoOutPut

{
    
if (!_myVideoOutPut) {
        
_myVideoOutPut = [[AVCaptureVideoDataOutput alloc]init];
        
[_myVideoOutPut setAlwaysDiscardsLateVideoFrames:YES];
        
[_myVideoOutPut setSampleBufferDelegate:(id<AVCaptureVideoDataOutputSampleBufferDelegate>)self queue:dispatch_get_main_queue()];
        
}
    
 return _myVideoOutPut;
    
}


- (void)configureDefaultComponents
{
  [_session addOutput:_metadataOutput];
    
    if ([_session canAddOutput:self.myVideoOutPut]) {
        [_session addOutput:self.myVideoOutPut];
    }
  
  if (_defaultDeviceInput) {
    [_session addInput:_defaultDeviceInput];
  }

   //设置代理 在主线程里刷新
  [_metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  if ([[_metadataOutput availableMetadataObjectTypes] containsObject:AVMetadataObjectTypeQRCode]) {
      /**
       *   设置扫码支持的编码格式(如下设置条形码和二维码兼容
       */
    [_metadataOutput setMetadataObjectTypes:@[
                                              AVMetadataObjectTypeQRCode,                AVMetadataObjectTypeEAN13Code,
                                        AVMetadataObjectTypeEAN8Code,
                                               AVMetadataObjectTypeCode128Code]];
  }
       // Preview addOutput
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    _previewLayer.frame=self.view.layer.bounds;
    
    
  if ([_previewLayer.connection isVideoOrientationSupported]) {
      
      _previewLayer.connection.videoOrientation = [[self class] videoOrientationFromInterfaceOrientation:self.interfaceOrientation];
      
  }
}

- (void)switchDeviceInput
{
  if (_frontDeviceInput) {
    [_session beginConfiguration];
    
    AVCaptureDeviceInput *currentInput = [_session.inputs firstObject];
    [_session removeInput:currentInput];
    
    AVCaptureDeviceInput *newDeviceInput = (currentInput.device.position == AVCaptureDevicePositionFront) ? _defaultDeviceInput : _frontDeviceInput;
    [_session addInput:newDeviceInput];
    
    [_session commitConfiguration];
  }
}

#pragma mark - Catching Button Events

- (void)cancelAction:(UIButton *)button
{
  [self stopScanning];
  
  if (_completionBlock) {
    _completionBlock(nil);
  }
  
  if (_delegate && [_delegate respondsToSelector:@selector(readerDidCancel:)]) {
    [_delegate readerDidCancel:self];
  }
}

- (void)switchCameraAction:(UIButton *)button
{
  [self switchDeviceInput];
}

#pragma mark - Controlling Reader

- (void)startScanning;
{
    if (![self.session isRunning]) {
        //开始捕获
        [self.session startRunning];
    }
    
    if(_timerScan)
    {
        [_timerScan invalidate];
        _timerScan = nil;
    }
    
    _timerScan = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scanAnimate) userInfo:nil repeats:YES];
}

- (void)stopScanning;
{
    if ([self.session isRunning]) {
        [self.session stopRunning];
    }
    if(_timerScan)
    {
        [_timerScan invalidate];
        _timerScan = nil;
    }
}

#pragma mark - AVCaptureMetadataOutputObjects Delegate Methods  AVCaptureMetadataOutput rectOfInterest

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection{
    CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL,sampleBuffer, kCMAttachmentMode_ShouldPropagate);
    NSDictionary *metadata = [[NSMutableDictionary alloc]initWithDictionary:(__bridge NSDictionary*)metadataDict];
    CFRelease(metadataDict);
    NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *) kCGImagePropertyExifDictionary] mutableCopy];
    float brightnessValue = [[exifMetadata objectForKey:(NSString *) kCGImagePropertyExifBrightnessValue] floatValue];
    if(brightnessValue<0.8){
        [_lightIcon setAlpha:1.0];
        [_topBtn setAlpha:1.0];
        [_lightButton setEnabled:YES];
    }else{
        if(!isLightOn){
            [_lightIcon setAlpha:0.0];
            [_topBtn setAlpha:0.0];
            [_lightButton setEnabled:NO];
        }
    }
//    NSLog(@"%f",brightnessValue);
}
                                                                                        

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    NSString *stringValue;
    if ([metadataObjects count] >0)
    {
            AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
            if ([metadataObject.type intValue] != 1)
            {
                stringValue = metadataObject.stringValue;
                [_session stopRunning];
                if (_completionBlock)
                {
                    [_beepPlayer play];
                    _completionBlock(stringValue);
                }
                if (_delegate && [_delegate respondsToSelector:@selector(reader:didScanResult:)])
                {
                    AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
                    stringValue = metadataObject.stringValue;
                    [_delegate reader:self didScanResult:stringValue];
                }
            }
    }
    


}



#pragma mark - Checking the Metadata Items Types

+ (BOOL)isAvailable
{
  @autoreleasepool {
      //获取摄像设备
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    if (!captureDevice) {
      return NO;
    }
    
    NSError *error;
      //创建输入流
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    
    if (!deviceInput || error) {
      return NO;
    }
    //创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    //设置代理 在主线程里刷新
    if (![output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {
      return NO;
    }
    
    return YES;
  }
}

#pragma mark - Checking RightBarButtonItem
-(void)clickRightBarButton:(UIBarButtonItem*)item
{
    self.detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- ( void )imagePickerController:( UIImagePickerController *)picker didFinishPickingMediaWithInfo:( NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (!image){
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
   
    
    NSArray *features = [self.detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
    
    if (features.count >=1) {
        CIQRCodeFeature *feature = [features objectAtIndex:0];
        NSString *scannedResult = feature.messageString;
        if (_completionBlock) {
            [_beepPlayer play];
            _completionBlock(scannedResult);
        }
        
        if (_delegate && [_delegate respondsToSelector:@selector(reader:didScanResult:)]) {
            [_delegate reader:self didScanResult:scannedResult];
        }
    }
}

#pragma mark - -
-(void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
